package com.mfl.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mfl.common.Result;
import com.mfl.constant.JwtResponseCodeConstant;
import com.mfl.context.BaseContext;
import com.mfl.properties.JwtProperties;
import com.mfl.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 管理端Jwt校验拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 判断当前拦截到的请求是否为Controller方法
        if(!(handler instanceof HandlerMethod)){
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        // 校验令牌
        try{
            log.info("管理端jwt校验：{}", token);
            Claims claims = JwtUtil.parseJwt(jwtProperties.getAdminSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get("adminId").toString());
            BaseContext.setCurrentId(userId);
            log.info("当前管理员id:{}", userId);
            log.info("jwt有效");
            return true;
        }catch (Exception ex){
            // 不通过，拦截请求，不向下传递，响应401状态码
            response.setStatus(401);
            // 创建 Result 对象来封装错误信息
            Result<Object> error = Result.error(JwtResponseCodeConstant.ADMIN_TOKEN_ERROR,"请先登录");
            log.info("无效token");
            // 设置响应的内容类型为 JSON，并设置字符集编码为utf-8
            response.setContentType("application/json;charset=utf-8");
            // 使用 ObjectMapper 将 Result 对象转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String jsonResponse = objectMapper.writeValueAsString(error);
                // 使用 response.getWriter() 将 JSON 字符串写入响应体
                try (PrintWriter out = response.getWriter()) {
                    out.print(jsonResponse);
                    out.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}
